package rozetka.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import rozetka.utils.ReportWriter;

import java.util.List;

/**
 * Created by foneox on 31.03.2014.
 */
public class SearchResultsPage extends BasePage {

    public static final String TYPICAL_SEARCH_URL = "http://rozetka.com.ua/search/";
    By searchResultTitlesLocator = By.cssSelector(".g-i-list-title>a");
    private List<WebElement> searchResultTitles;

    public SearchResultsPage(WebDriver driver) {
        super(driver);
    }

    private static final By resultsRedirectedItemLabelLocator = new By
            .ByXPath(".//*[@id='head_banner_container']//*[@class = 'aligned-center']");
    private static final By resultsItemLabelLocator = new By.ByXPath(".//*[@id='head_banner_container']//h1");

    public Boolean areSearchResultsMatchingTheQuery(String query) {
        WebElement resultsForItemLabel;

        if (driver.getCurrentUrl().contains(TYPICAL_SEARCH_URL)){
            resultsForItemLabel = driver.findElement(resultsItemLabelLocator);
        }else{
            resultsForItemLabel = driver.findElement(resultsRedirectedItemLabelLocator);
        }

        return resultsForItemLabel.getText().contains(query);
    }

    public ProductPage openProductPage(String fullProductTitle) {
        //Fixme: works only for first page with results. Should be impoved to include all results
        searchResultTitles = driver.findElements(searchResultTitlesLocator);
        for (int i = 0; i<searchResultTitles.size(); i++){
            WebElement searchResultTitleElement = searchResultTitles.get(i);
            String searchResultTitle = searchResultTitleElement.getText();
            if (searchResultTitle.contains(fullProductTitle)){
                searchResultTitleElement.click();
                return new ProductPage(driver);
            }
        }
        ReportWriter.error("There are no products found matching title: "+ fullProductTitle);
        return null;
    }
}
